package net.worldscale.xp.wslib.wsxml.impl;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.worldscale.xp.wslib.wsxml.DomBuilder;
import net.worldscale.xp.wslib.wsxml.WsXML;
import net.worldscale.xp.wslib.wsxml.sax.SaxParser;
import net.worldscale.xp.wslib.wsxml.sax.SaxParserFactory;
import net.worldscale.xp.wspr.ModuleInfo;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

final class ImplWsXML extends WsXML {

    public ImplWsXML() {
    }

    @Override
    public DOMImplementation getDOMImplementation() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.getDOMImplementation();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Document createDOM(InputStream is, String mime) {
        try {
            final SaxParser parser = this.getSaxParserFactory().newParser();
            if (mime != null) {
                if (mime.startsWith("text/html")) {
                    parser.setProperty("mime", mime);
                }
            }
            final DomBuilder builder = this.newDOMBuilder();
            parser.parse(is, builder);
            return builder.getDOM();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public DomBuilder newDOMBuilder() {
        return new ImplDomBuilder();
    }

    @Override
    public SaxParserFactory getSaxParserFactory() {
        return new SaxParserFactory() {

            @Override
            public SaxParser newParser() {
                return new ImplSaxParser();
            }
        };
    }

    @Override
    public ModuleInfo getInfo() {
        return (new WsXmlFactory()).getInfo();
    }
}
